package service.rocksea.com.serviceapp;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import static android.content.ContentValues.TAG;

/**
 * Created by 吴志华 on 2017/10/18.
 *
 */

public class CommThread extends Thread
{
    public final  static int PHONE_PORT = 5002;
    private WifiManager.WifiLock wifiLock = null;
    private PowerManager.WakeLock wakeLock = null;
    private boolean isTurnDown = false;


    private DatagramSocket socket;
    private Context context;
    private final WriteDataThread writeDataThread;


    public static DatagramSocket createWifiSocket()
    {
        try
        {
            DatagramSocket wifiSocket = new DatagramSocket(PHONE_PORT);//5002;
            wifiSocket.setSoTimeout(10*1000);
            return wifiSocket;
        }
        catch (SocketException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public CommThread(DatagramSocket socket, Context context) throws Exception {
        this.socket = socket;
        this.context = context;
        if (this.socket==null)
            throw  new Exception("获取SOCKET失败!!!");
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
        if (wifiLock!=null)
            wifiLock.acquire();
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
        if (wakeLock!=null)
            wakeLock.acquire();
        writeDataThread = new WriteDataThread(socket);
        writeDataThread.start();
        HeartThread heartThread = new HeartThread(writeDataThread);
        heartThread.start();
    }
    @Override
    public void run()
    {
        super.run();
        byte[] bytes = new byte[4096];
        DatagramPacket recPackage = new DatagramPacket(bytes,bytes.length);

        while (!isTurnDown)
        {
            try
            {
                socket.receive(recPackage);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            byte[] data = recPackage.getData();
            int len = recPackage.getLength();
            if (data==null || data.length==0 || len==0)
                continue;
            receive(data, len,recPackage);

        }
    }
    public void turnDown()
    {
        isTurnDown = true;
        writeDataThread.turnDown();
    }
    private ReceiveBuffer receiveBuffer = new ReceiveBuffer();
    private void receive(byte[] data,int len,DatagramPacket datagramPacket)
    {
        if (!receiveBuffer.recieve(data,len))
        {
            return;
        }
        receiveBuffer.m_start = 0;
        UDPPacket udpPacket;
        while ((udpPacket=receiveBuffer.checkSumPackage(receiveBuffer.m_start))!=null)
        {
            String command = Integer.toHexString(udpPacket.cCommand);
            Log.i(TAG, "receive: "+command);
            switch (udpPacket.cCommand)
            {
                case UDPPacket.JS_LoginResponse:   //发送报检单的登录回复
                    Log.d(TAG, "receive: JS_LoginResponse");
                    break;
                case UDPPacket.PLAN_FILE:           //报检单文件
                    //writeDataThread.handleRequestPlanRespone(udpPacket);
                    break;
                case UDPPacket.REQUEST_PLAN:
                    break;
                case UDPPacket.PLAN_FILE_RESPONE:
                    writeDataThread.handleRequestPlanRespone(udpPacket);
                    break;
            }
            receiveBuffer.m_start += udpPacket.length();
        }
    }


    public void sendJson(String json)
    {
        try {
            writeDataThread.sendJson(json);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

}
